package com.springweb;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.el.parser.JJTELParserState;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.springweb.service.AdminService;
import com.springweb.simpleform.EmployeeDetails;
import com.springweb.validator.EmployeeValidator;

@Controller
// now this is also a kind of bean that has been registered inside container
// as a controller which intercept request from user through front controller.
public class WelcomeController {
	// welcomeController
   private Logger logger=Logger.getLogger(WelcomeController.class);
   
	@RequestMapping(value = "welcome")
	//return type  ?    parameter type.. 
	public ModelAndView getWelcomePage(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("welcome");
		System.out.println("inside get welcome page method..");
		mav.addObject("customMsg", "Hi this msg is in model object");
		return mav;
	}

	@RequestMapping(value = "index")
	public ModelAndView getIndexPage(HttpSession session) {
		ModelAndView mav = new ModelAndView("index");
	    logger.debug("inside getindexpage method");    
		mav.addObject("customMsg", "Hi this msg is in model object");
		return mav;
	}


	@RequestMapping(value="submitDetails")
	public ModelAndView submitDetails(@RequestParam(required=false)String userName,@RequestParam(required=true) String password){
		ModelAndView mav=new ModelAndView("submittedDetails");
		System.out.println("Inside Submitted details  handler method.. ");
		/*String userName=request.getParameter("userName");*/
		System.out.println("User Name entered : "+userName);
		mav.addObject("userName", userName);

		return mav;
	}


	@RequestMapping(value="registerEmployee")
	public ModelAndView getRegisterPage(){

		ModelAndView mav=new ModelAndView("springForm");

		mav.addObject("employee", new EmployeeDetails());
		mav.addObject("admin",new AdminService());

		return mav;
	}

	@RequestMapping(value="submitEmployeeDetails")
	public ModelAndView submitEmployeeDetails(@ModelAttribute("employee") @Valid  EmployeeDetails employee, BindingResult result,HttpServletRequest request){
		ModelAndView mav=new ModelAndView();
		EmployeeValidator employeeValidator=new EmployeeValidator();
		employeeValidator.validate(employee, result);
		if(result.hasErrors()){
			System.out.println("valiation error found");
			mav.setViewName("springForm");
			mav.addObject("employee", employee);

		}else {
			System.out.println("process result.");
			System.out.println(employee);
			if(null!=employee.getImage()){

				MultipartFile image=employee.getImage();
				   System.out.println("Uploaded file mime type :"+ image.getContentType());
				   
				  try {
					 
					FileOutputStream outputStream=new FileOutputStream("/home/rajeev/"+image.getOriginalFilename());
					outputStream.write(image.getBytes());
					outputStream.flush();
					outputStream.close();
					
					
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}


			}

			mav.setViewName("reigsterSuccess");
		}
		return mav;
	}

	// WEB SERVICES ARE OF TWO TYPES 
	// SOAP BASED - simple object access protocol  (Havey - data transmit over network using XML header ) 
	//REST BASED -- Reprentation state transfer  (light weight -- generally used json)
	// JSON -- java script object notation. 

	@RequestMapping(value="{orderId}/details.htm")
	@ResponseBody
	public void getOrderDetails(@PathVariable String orderId, HttpServletResponse response){
		// fetch details for orderId from database. 
		response.setContentType("application/json");
		System.out.println("Fetching order details from database for orderId:"+orderId);

		JSONObject jsonObject=new JSONObject();
		jsonObject.put("orderId", orderId);
		jsonObject.put("OrderedUser", "Demo User");
		//22122, 221223
		JSONArray array=new JSONArray();
		array.put(22122);
		array.put(2223366);
		jsonObject.put("prevOrders",array); 

		try {
			response.getWriter().write(jsonObject.toString(2));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	@PostConstruct
	public void init(){
		System.out.println("inside init method");
		logger.info("logger info is being called..");
	}
}
